package com.csyf.manager.schedule;

import com.csyf.manager.channel.base.ServiceEnum;
import com.csyf.manager.channel.cspay.CspayBiz;
import com.csyf.manager.channel.nmpay.NmPayBiz;
import com.csyf.manager.channel.xiaojifu.XiaojifuBiz;
import com.csyf.manager.entity.SysPayment;
import com.csyf.manager.service.OrderBiz;
import com.csyf.manager.service.OrderService;
import com.csyf.manager.service.PayMentBiz;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 代付订单 定时任务
 * @auther: casper
 * @date: 2018/12/4 14:09
 * @param:
 * @return:
 */
@Slf4j
@Component
public class MinuteProcessSchedule implements Job {


    @Autowired
    private OrderService orderService;


    @Autowired
    private OrderBiz orderBiz;

    @Autowired
    private PayMentBiz payMentBiz;

    @Autowired
    private CspayBiz cspayBiz;

    @Autowired
    private NmPayBiz nmPayBiz;

    @Autowired
    private XiaojifuBiz xiaojifuBiz;


    @Autowired
    private Environment env;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("=================================");
        log.info("MinuteProcessSchedule");
        log.info("===============================>>");


        String[] activeProfiles = env.getActiveProfiles();
        List<String> acts = Arrays.asList(activeProfiles);

        log.info("scheduled 2: {} ,profile: {}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), env.getActiveProfiles());


        log.info("处理代付未知状态的订单");
        List<SysPayment> sysPayments = payMentBiz.queryunknowOrder();

        // 第一种：根据代付类型 代付/同步订单处理
        syncDfOrder(sysPayments, acts);
    }


    public void syncDfOrder(List<SysPayment> sysPayments, List<String> acts) {

        for (SysPayment sysPayment : sysPayments) {

            Date createTime = sysPayment.getCreateTime();
            Date curDate = new Date();

            //如果当前时间和创建时间 小于1min 则不进行查询;
            if (curDate.getTime() - createTime.getTime() < 60000) {
                continue;
            }

            ServiceEnum serviceEnum = ServiceEnum.valueOf(sysPayment.getService());
            switch (serviceEnum) {
                case NM_ALI_DF_DZ:
                case NM_ALI_DF_NO:
                    if (acts.contains("prod")) {
                        nuomipayment(sysPayment);
                    }
                    break;
                case XJ_ALI_DF_NO:
                case XJ_ALI_DF_DZ:
                    if (acts.contains("prod")) {
                        xiaojiprocess(sysPayment);
                    }
                    break;
            }
        }
    }

    /*************************************代付查询***********************************************/

    private void nuomipayment(SysPayment sysPayment) {
        try {
            Map map = nmPayBiz.doqueryDf(sysPayment.getOutTradeNo(), sysPayment.getMchId(), sysPayment.getSrcMchId());
            log.info(map.toString());

            if ("FAILED".equals(map.get("tradeStatus").toString())) {
                payMentBiz.doFail(sysPayment.getOutTradeNo(), map.get("tradeStatus").toString() + "|" + map.get("tradeStatusDesc"));
            } else if ("SUCCESS".equals(map.get("tradeStatus").toString())) {
                payMentBiz.doSuccess(sysPayment.getOutTradeNo(), map.get("tradeStatus") + "|" + "代付成功");
            } else if ("PROCESS".equals(map.get(map.get("tradeStatus").toString()))) {
                payMentBiz.doUnkunow(sysPayment.getOutTradeNo(), map.get("tradeStatus") + "|" + "处理中");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 小机 支付宝代付
     *
     * @param sysPayment
     */
    private void xiaojiprocess(SysPayment sysPayment) {
        Map<String, String> rspMap = xiaojifuBiz.doqueryDf(sysPayment.getOutTradeNo(), sysPayment.getMchId(), sysPayment.getSrcMchId());
        if (null == rspMap || rspMap.isEmpty()) {
            return;
        }

        String data = rspMap.get("data");
        if ("1".equals(data)) {
            payMentBiz.doSuccess(sysPayment.getOutTradeNo(), "0000|代付成功");
        } else if ("0".equals(data)) {
            payMentBiz.doUnkunow(sysPayment.getOutTradeNo(), "0001|处理中");
        } else if ("-1".equals(data)) {
            payMentBiz.doFail(sysPayment.getOutTradeNo(), "9998|代付失败");
        }

    }



    private void ecpayprocess(SysPayment sysPayment) {
        try {
            Map<String,String> resultMap = cspayBiz.querydfOrder(sysPayment.getOutTradeNo(), sysPayment.getMchId(), sysPayment.getSrcMchId());

            //交易状态(1-处理中，2-失败，3-成功)
            String payStatus = resultMap.get("payStatus");
            if ("3".equals(payStatus)) {
                payMentBiz.doSuccess(sysPayment.getOutTradeNo(), "0000" + "|" + "代付成功");
            } else if ("1".equals(payStatus)) {
                payMentBiz.doUnkunow(sysPayment.getOutTradeNo(), "1" + "|" + "处理中");
            } else {
                String payMsg = resultMap.get("payMsg");
                payMentBiz.doFail(sysPayment.getOutTradeNo(), payStatus + "|" + payMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




}
